package com.example.administrator.jim.addresslist;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.example.administrator.jim.R;
import com.example.administrator.jim.adapter.ContactsAdapter;
import com.example.administrator.jim.bean.Contact;
import com.example.administrator.jim.bean.NewFriendBean;
import com.example.administrator.jim.dbbean.YanZhengBean;
import com.example.administrator.jim.imuisample.messages.MessageListActivity;
import com.example.administrator.jim.minterface.AddressListClickListener;
import com.example.administrator.jim.utils.DBUtils;
import com.example.administrator.jim.value.YanZhengValue;
import com.github.promeg.pinyinhelper.Pinyin;
import com.gjiazhe.wavesidebar.WaveSideBar;
import com.sdsmdg.tastytoast.TastyToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.model.UserInfo;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import q.rorbin.badgeview.Badge;

/**
 * Created by BarBrothers on 2017/12/19.
 */

public class AddressListView extends RelativeLayout {
    private View mView;
    private Context mContext;
    //获取好友列表的标记
    private int friendlistsize;
    private int friendlistflag=0;
    //======华丽的分割线==========
    public static ArrayList<Contact> contacts = new ArrayList<>();
    @BindView(R.id.addresslist_contacts)
    RecyclerView rvContacts;
    @BindView(R.id.addresslist_side_bar)
    WaveSideBar sideBar;
    public static ArrayList<NewFriendBean> mdatas;
    public static ContactsAdapter mContactsAdapter;

    public AddressListView(Context context) {
        this(context,null);
    }

    public AddressListView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AddressListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;
        mView=View.inflate(context, R.layout.view_addresslist, this);
        ButterKnife.bind(mView);
        JMessageClient.registerEventReceiver(this);
        initData();
    }

    private void initView() {
        rvContacts.setLayoutManager(new LinearLayoutManager(mContext));
        mContactsAdapter = new ContactsAdapter(mContext,contacts, R.layout.item_contacts);
        mContactsAdapter.setAddressListClickListener(new AddressListClickListener() {
            @Override
            public void onItemClick(View v, Badge badge, int pos) {
                if(pos==0){
                    badge.setBadgeNumber(0);
                    contacts.get(pos).setMessageflag(0);
                    mContext.startActivity(new Intent(mContext,NewFriendActivity.class));
                }else if(pos==1){
                    TastyToast.makeText(getContext(), "暂未开通", TastyToast.LENGTH_SHORT, TastyToast.INFO);
                }else if(pos>1) {
                    Intent intent = new Intent(mContext, MessageListActivity.class);
                    intent.putExtra("username",contacts.get(pos).getUsername());
                    mContext.startActivity(intent);
                }
            }
        });
        rvContacts.setAdapter(mContactsAdapter);
        sideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {
                for (int i=2; i<contacts.size(); i++) {
                    if (contacts.get(i).getIndex().equals(index)) {
                        ((LinearLayoutManager) rvContacts.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });
    }

    private void initData() {
        contacts.addAll(Contact.getTopTwoContacts());
        friendlistflag=0;
        mdatas=new ArrayList<>();
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(final ObservableEmitter<Integer> e) throws Exception {
                ContactManager.getFriendList(new GetUserInfoListCallback() {
                    @Override
                    public void gotResult(int i, String s, final List<UserInfo> list) {
                        if (i==0){
                            friendlistsize=list.size();
                            for (int x=0;x<list.size();x++){
                                UserInfo u=list.get(x);
                                final Contact contact;
                                if(!u.getNickname().equals("")){
                                    if(Pinyin.isChinese(u.getNickname().charAt(0))){
                                        contact=new Contact( Pinyin.toPinyin(u.getNickname().charAt(0)).substring(0,1).toUpperCase(),u.getNickname());
                                    }else {
                                        contact=new Contact(u.getUserName().substring(0,1).toUpperCase(),u.getNickname());
                                    }
                                }else {
                                    contact=new Contact(u.getUserName().substring(0,1).toUpperCase(),u.getNickname());
                                }
                                contact.setUsername(u.getUserName());
                                u.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                                    @Override
                                    public void gotResult(int i, String s, Bitmap bitmap) {
                                        contact.setBitmap(bitmap);
                                        contacts.add(contact);
                                        friendlistflag++;
                                        e.onNext(friendlistflag);
                                    }
                                });
                            }
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if(integer==friendlistsize){
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Collections.sort(contacts);
                                    initView();
                                }
                            }, 200);
                        }
                    }
                });
        initYanzhengList();
    }

    //收到好友验证
    public void onEventMainThread(final ContactNotifyEvent event) {
        for (Contact c:contacts) {
            if(c.getName().equals("验证消息")){
                c.setMessageflag(c.getMessageflag()+1);
                mContactsAdapter.notifyDataSetChanged();
            }
        }
        switch (event.getType()) {
            case invite_received://收到好友邀请
                boolean isinsert = DBUtils.insertYanZhengFriendData(event.getFromUsername(), event.getReason(), YanZhengValue.YANZHENG_NEWFRIEND, event.getfromUserAppKey());
                if(isinsert){
                    NewFriendBean newFriendBean = new NewFriendBean();
                    newFriendBean.setFlag(YanZhengValue.YANZHENG_NEWFRIEND);
                    Observable.create(new ObservableOnSubscribe<NewFriendBean>() {
                        @Override
                        public void subscribe(final ObservableEmitter<NewFriendBean> e) throws Exception {
                            final NewFriendBean newFriendBean=new NewFriendBean();
                            newFriendBean.setRes(event.getReason());
                            newFriendBean.setFlag(YanZhengValue.YANZHENG_NEWFRIEND);
                            newFriendBean.setAppk(event.getfromUserAppKey());
                            newFriendBean.setUsername(event.getFromUsername());
                            JMessageClient.getUserInfo(event.getFromUsername(), event.getfromUserAppKey(), new GetUserInfoCallback() {
                                @Override
                                public void gotResult(int i, String s, UserInfo userInfo) {
                                    if(i==0){
                                        if(userInfo.getNickname().equals("")){
                                            newFriendBean.setName(userInfo.getUserName());
                                        }else {
                                            newFriendBean.setName(userInfo.getNickname());
                                        }
                                        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                            @Override
                                            public void gotResult(int i, String s, Bitmap bitmap) {
                                                newFriendBean.setBitmap(bitmap);
                                                e.onNext(newFriendBean);
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<NewFriendBean>() {
                        @Override
                        public void accept(NewFriendBean friend) throws Exception {
                            mdatas.add(0,friend);
                        }
                    });
                }else {
                    NewFriendBean newFriendBean=null;
                    for(int x=0;x<mdatas.size();x++){
                        if(mdatas.get(x).getUsername().equals(event.getFromUsername())){
                            newFriendBean = mdatas.get(x);
                            mdatas.remove(x);
                            break;
                        }
                    }
                    newFriendBean.setRes(event.getReason());
                    mdatas.add(0,newFriendBean);
                }
                break;
            case invite_accepted://对方接收了你的好友邀请
                NewFriendBean newFriendBean1=null;
                for(int x=0;x<mdatas.size();x++){
                    if(mdatas.get(x).getUsername().equals(event.getFromUsername())){
                        newFriendBean1 = mdatas.get(x);
                        mdatas.remove(x);
                        break;
                    }
                }
                newFriendBean1.setFlag(YanZhengValue.YANZHENG_JIESHOU);
                mdatas.add(0,newFriendBean1);
                DBUtils.updateYanZhengFriendFlag(event.getFromUsername(),YanZhengValue.YANZHENG_JIESHOU);
                //加入到通讯录
                Contact c;
                if(!newFriendBean1.getName().equals("")){
                    if(Pinyin.isChinese(newFriendBean1.getName().charAt(0))){
                        c=new Contact( Pinyin.toPinyin(newFriendBean1.getName().charAt(0)).substring(0,1).toUpperCase(),newFriendBean1.getName());
                    }else {
                        c=new Contact(newFriendBean1.getUsername().substring(0,1).toUpperCase(),newFriendBean1.getUsername());
                    }
                }else {
                    c=new Contact(newFriendBean1.getUsername().substring(0,1).toUpperCase(),newFriendBean1.getUsername());
                }
                c.setUsername(newFriendBean1.getUsername());
                c.setBitmap(newFriendBean1.getBitmap());
                contacts.add(c);
                Collections.sort(contacts);
                mContactsAdapter.notifyDataSetChanged();
                break;
            case invite_declined://对方拒绝了你的好友邀请
                NewFriendBean newFriendBean=null;
                for(int x=0;x<mdatas.size();x++){
                    if(mdatas.get(x).getUsername().equals(event.getFromUsername())){
                        newFriendBean = mdatas.get(x);
                        mdatas.remove(x);
                        break;
                    }
                }
                newFriendBean.setFlag(YanZhengValue.YANZHENG_JUJUE);
                mdatas.add(0,newFriendBean);
                DBUtils.updateYanZhengFriendFlag(event.getFromUsername(),YanZhengValue.YANZHENG_JUJUE);
                break;
            case contact_deleted://对方将你从好友中删除

                break;
            default:
                break;
        }
    }
    private void initYanzhengList() {
        Observable.create(new ObservableOnSubscribe<NewFriendBean>() {
            @Override
            public void subscribe(final ObservableEmitter<NewFriendBean> e) throws Exception {
                List<YanZhengBean> list = DBUtils.queryYanZhengFriendDatas();
                for(YanZhengBean yanZhengBean:list){
                    final NewFriendBean newFriendBean=new NewFriendBean();
                    newFriendBean.setRes(yanZhengBean.getReson());
                    Log.e("测试====",yanZhengBean.getFalg()+"");
                    newFriendBean.setFlag(yanZhengBean.getFalg());
                    newFriendBean.setAppk(yanZhengBean.getAppk());
                    newFriendBean.setUsername(yanZhengBean.getName());
                    JMessageClient.getUserInfo(yanZhengBean.getName(), yanZhengBean.getAppk(), new GetUserInfoCallback() {
                        @Override
                        public void gotResult(int i, String s, UserInfo userInfo) {
                            if(i==0){
                                if(userInfo.getNickname().equals("")){
                                    newFriendBean.setName(userInfo.getUserName());
                                }else {
                                    newFriendBean.setName(userInfo.getNickname());
                                }
                                userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                    @Override
                                    public void gotResult(int i, String s, Bitmap bitmap) {
                                        newFriendBean.setBitmap(bitmap);
                                        e.onNext(newFriendBean);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<NewFriendBean>() {
            @Override
            public void accept(NewFriendBean friend) throws Exception {
                mdatas.add(friend);
            }
        });
    }
}
